import { _decorator, Toggle } from 'cc';
import { VMBase } from './VMBase';

const { ccclass, property, menu } = _decorator;

@ccclass('VMToggle')
@menu("StateSignals/VMToggle")
export class VMToggle extends VMBase {
    useTemplate = false;

    @property({ tooltip: '要监听的路径' })
    watchPath = '';

    protected onLoad(): void {
        super.onLoad();
        this.node.on('click', this.onToggleClick, this);
    }

    protected onDestroy(): void {
        this.node.off('click', this.onToggleClick, this);
    }

    onValueInit() {
        this.setToggleValue(this.getValue(this.watchPath, false));
    }

    onValueChanged(current: any, prev: any) {
        this.setToggleValue(current);
    }

    private setToggleValue(value: boolean) {
        const toggle = this.node.getComponent(Toggle);
        if (toggle) {
            toggle.isChecked = value;
        }
    }

    private onToggleClick(e: Toggle) {
        // 下一帧更新，保证值更新
        this.scheduleOnce(() => {
            this.setValue(this.watchPath, e.isChecked);
        }, 0);
    }
}
